<?php

namespace xcxApi\modules\user\controllers;

use common\components\fast_api\Controller;
use common\components\wtools\tools\Model;
use common\Tools;
use xcxApi\models\db\MpUser;

class CenterController extends Controller
{
    /**
     * 获取用户信息
     * @desc 获取小程序的用户信息
     * @return array
     */
    public function actionIndex()
    {
        $mpUser = \Yii::$app->user->identity;
        return $this->apiSuccess(['mpUser' => MpUser::getFilterShow($mpUser)]);
    }

    /**
     * 修改用户信息
     * @desc 修改小程序的用户信息
     * @param string $nickname
     * @param string $avatar base64
     * @param string $mobile
     * @return array
     */
    public function actionSetting($nickname, $avatar = null, $mobile = null)
    {
        $mpUser = \Yii::$app->user->identity;
        $mpUser->nickname = $nickname;
        $box = imagettfbbox(16, 0, \Yii::getAlias('@common/fonts/TEMPSITC.TTF'), $nickname);
        $textWidth = $box[2] - $box[0]; // 返回文本宽度
        if ($textWidth > 250) {
            return $this->apiError("昵称长度过长");
        }
        if ($mobile) $mpUser->mobile = $mobile;
        if ($avatar) {
            $url = \Yii::$app->fs->uploadByBase64($avatar);
            $mpUser->avatar = $url;
        }
        if (!$mpUser->save()) {
            return $this->apiError(Model::getModelError($mpUser));
        }
        return $this->apiSuccess(['mpUser' => MpUser::getFilterShow($mpUser)], "保存成功");
    }

    /**
     * 解密小程序手机号
     * @desc 解密小程序手机号
     * @param string $code
     * @param string $encryptedData
     * @param string $iv
     * @return array
     */
    public function actionDecryptMpMobile($code, $encryptedData = null, $iv = null)
    {
        $xcx = \Yii::$app->xcx;
        $res2 = $xcx->decryptXcxMoblie($code);
        return $this->apiSuccess([
            'mobile' => $res2['purePhoneNumber'],
        ]);
    }
}
